package com.yang.utils;

import com.yang.utils.info.QQEmailBean;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;

/**
 * @author yangdacheng
 * @title: SendEmailUtils
 * @projectName note_api
 * @description: TODO
 * @date 2022/3/3 7:18 下午
 */
@Component
public class SendEmailUtils {

    @Resource
    private JavaMailSender mailSender;
    @Resource
    private QQEmailBean qqEmailBean;

    /**
     * 发送邮件
     * @param toEmail 接受者
     * @param sendText 发送消息
     * @param subject 发送主题
     */
    public void sendCode(String toEmail, String sendText,String subject){
        //发送邮件
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom(qqEmailBean.getUsername());
        mailMessage.setTo(toEmail);
        mailMessage.setText(sendText);
        mailMessage.setSubject(subject);
        mailSender.send(mailMessage);
    }

    /**
     * 发送html格式的邮件
     * @param toEmail
     * @param sendText
     * @param subject
     */
    public void sendHtml(String toEmail, String sendText,String subject){
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
            mimeMessageHelper.setFrom(qqEmailBean.getUsername());
            mimeMessageHelper.setTo(toEmail);
            mimeMessageHelper.setText(sendText,true);
            mimeMessage.setSubject(subject);
            mailSender.send(mimeMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
